import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import 'package:localstorage/localstorage.dart';
import 'dart:convert';

class StorageManager {
  /// app全局配置 eg:theme
  static SharedPreferences? sharedPreferences;

  /// 临时目录 eg: cookie
  static Directory? temporaryDirectory;

  /// 必备数据的初始化操作
  /// 由于是同步操作会导致阻塞,所以应尽量减少存储容量
  static Future init() async {
    // async 异步操作
    // sync 同步操作
    temporaryDirectory = await getTemporaryDirectory();
    sharedPreferences = await SharedPreferences.getInstance();
    return initLocalStorage();
  }

  static void setItem(String key, dynamic value) {
    // 对accounts特殊处理，使用json.encode序列化
    if (key == 'accounts' && (value is List || value is Map)) {
      localStorage.setItem(key, json.encode(value));
    }
    // 其他类型数据的处理
    else if (value is Map || value is List) {
      value = value.toString();
      localStorage.setItem(key, value);
    } else {
      localStorage.setItem(key, value);
    }
  }

  static dynamic getItem(String key) {
    final catchStr = localStorage.getItem(key);
    if (key == 'accounts' && catchStr != null) {
      try {
        // 尝试将字符串解析为List<dynamic>
        return json.decode(catchStr);
      } catch (e) {
        print('解析accounts失败: $e');
        return null;
      }
    } else {
      return catchStr;
    }
  }

  static void clear() {
    localStorage.clear();
  }
}
